package oop.ex3.nameserver.actions;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;

import oop.ex3.messages.MessageInterface;
import oop.ex3.messages.PeerInfoMessage;
import oop.ex3.messages.SimpleMessage;
import oop.ex3.messages.ValidHeaders;
import oop.ex3.messages.exception.InvalidHeaderException;


import oop.ex3.nameserver.NSContext;
import oop.ex3.sockets.ClientSocket;

public class SendServers extends NsAction{

	public SendServers(NSContext context){
		super(context);
		
	}
	
	@Override
	public boolean run(ClientSocket socket, MessageInterface msg) {
		Iterator nsIterator = _context.viewNS();
		while (nsIterator.hasNext()){
			InetSocketAddress server = (InetSocketAddress) nsIterator.next();
			//TODO check if you need to send some other header
			PeerInfoMessage msg1 = new PeerInfoMessage
			(ValidHeaders.CONTAINNAMESERVER, server);
			try {
				socket.SendMessage(msg1);	
			} catch (Exception e){
				return false;
			}
			
		} 
		try {
			socket.SendMessage(new SimpleMessage(ValidHeaders.ENDLIST));
		} catch (IOException e) {
			return false;
		} catch (InvalidHeaderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

}
